<?php
namespace Lib\Encryption\Driver;

use Lib\Encryption\DriverAbstract,
    Lib\Encryption\DriverInterface,
    Lib\Encryption\DriverException;
/**
 * Enter description here ...
 * 
 * @author diotheos
 * @package Encryption
 */
class Mcrypt extends DriverAbstract implements DriverInterface{
    
    private $_iv_size;
    
    public function __construct(){
        if(!extension_loaded('mcrypt')){
            throw new DriverException('Extension "MCRYPT" is not loaded');
        }
        
        $this->_iv_size = mcrypt_get_iv_size(MCRYPT_XTEA, MCRYPT_MODE_ECB);
        parent::__construct();
    }
    
    /**
     * (non-PHPdoc)
     * @see Lib\Encryption.DriverAbstract::encode()
     */
    public function encode($item){
        $iv = mcrypt_create_iv($this->_iv_size, MCRYPT_RAND);
        $enc = mcrypt_encrypt(MCRYPT_XTEA, $this->_secret, $item, MCRYPT_MODE_ECB, $iv);
        
        return urlencode($enc);
    }

    /**
     * (non-PHPdoc)
     * @see Lib\Encryption.DriverAbstract::decode()
     */
    public function decode($hash){
        $hash = urldecode($hash);
        $iv = mcrypt_create_iv($this->_iv_size, MCRYPT_RAND);
        $crypttext = mcrypt_decrypt(MCRYPT_XTEA, $this->_secret, $hash, MCRYPT_MODE_ECB, $iv);
        $crypttext = rtrim($crypttext, "\0\4");
        
        return $crypttext;
    }
}